package tech.runchen.gz5055.oms.modules.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import tech.runchen.gz5055.oms.common.constant.Constant;
import tech.runchen.gz5055.oms.common.utils.PageInfo;
import tech.runchen.gz5055.oms.common.utils.Query;
import tech.runchen.gz5055.oms.common.utils.StringUtils;
import tech.runchen.gz5055.oms.common.utils.poi.head.ImportBarcodeExcel;
import tech.runchen.gz5055.oms.modules.system.entity.BarcodeEntity;
import tech.runchen.gz5055.oms.modules.system.entity.ProductEntity;
import tech.runchen.gz5055.oms.modules.system.mapper.BarcodeMapper;
import tech.runchen.gz5055.oms.modules.system.service.IBarcodeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import tech.runchen.gz5055.oms.modules.system.service.ICommonService;
import tech.runchen.gz5055.oms.modules.system.service.IProductService;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 商品标签条码表 服务实现类
 * </p>
 *
 * @author zzj
 * @since 2023-10-19
 */
@Service
public class BarcodeServiceImpl extends ServiceImpl<BarcodeMapper, BarcodeEntity> implements IBarcodeService {

    private final static Logger logger = LoggerFactory.getLogger(BarcodeServiceImpl.class);

    @Autowired
    private IProductService productService;
    @Autowired
    private ICommonService commonService;

    @Override
    public PageInfo queryPage(Map<String, Object> params) {

        Object productId = params.get("productId");
        String productInfo = (String) params.get("productInfo");
        String barcode = (String) params.get("barcode");

        IPage<BarcodeEntity> page = this.page(
                new Query<BarcodeEntity>().getPage(params),
                new QueryWrapper<BarcodeEntity>()
                        .eq(Objects.nonNull(productId), "product_id", productId)
                        .like(StringUtils.isNotBlank(productInfo), "product_info", productInfo)
                        .like(StringUtils.isNotBlank(barcode), "barcode", barcode)
        );

        return new PageInfo(page);
    }

    @Override
    public PageInfo queryUseReportList(Map<String, Object> params) {
        Object startTime = params.get("startTime");
        Object endTime = params.get("endTime");
        long curPage = 1;
        long limit = 10;
        if (params.get(Constant.PAGE) != null) {
            curPage = Long.parseLong((String) params.get(Constant.PAGE));
        }
        if (params.get(Constant.LIMIT) != null) {
            limit = Long.parseLong((String) params.get(Constant.LIMIT));
        }
        StringBuffer countSql = new StringBuffer("select count(barcode.barcode) from barcode_tb barcode ");
        StringBuffer selectSql = new StringBuffer("select FROM_UNIXTIME(barcode.outbound_time / 1000 +28800, '%Y-%m-%d %H:%i:%s') as outboundTime, product.product_name as productName,product.model, barcode.barcode, address.name as outboundAddress, user.nick_name as outboundUserName from barcode_tb barcode ");
        StringBuffer sql = new StringBuffer("");
        sql.append("LEFT JOIN product_tb product on product.id = barcode.product_id ");
        sql.append("LEFT JOIN user_tb user on user.id = barcode.outbound_user_id ");
        sql.append("LEFT JOIN address_tb address on address.id = barcode.outbound_address_id ");
        sql.append("where barcode.outbound_user_id is not NULL and barcode.outbound_address_id is not NULL and barcode.order_id is not NULL ");
        if (startTime != null && endTime != null) {
            sql.append("AND barcode.outbound_time > " + startTime + " ");
            sql.append("AND barcode.outbound_time <= " + endTime + " ");
        }
        int totalCount = commonService.selectCountBySql(countSql.append(sql).toString());
        sql.append(" limit " + (curPage * limit) + "," + ((curPage + 1) * limit));
        List<Map<String, Object>> list = commonService.selectObjectBySql(selectSql.append(sql).toString());
        return new PageInfo(list, totalCount, (int) limit, (int) curPage);
    }

    @Override
    public List<BarcodeEntity> querySelect(Map<String, Object> params) {

        Object productId = params.get("productId");
        String productInfo = (String) params.get("productInfo");
        String barcode = (String) params.get("barcode");

        List<BarcodeEntity> list = this.list(
                new QueryWrapper<BarcodeEntity>()
                        .eq(Objects.nonNull(productId), "product_id", productId)
                        .like(StringUtils.isNotBlank(productInfo), "product_info", productInfo)
                        .like(StringUtils.isNotBlank(barcode), "barcode", barcode)
        );

        return list;
    }

    @Override
    public BarcodeEntity queryInfoByCode(String code) {
        BarcodeEntity barcode = this.getOne(new QueryWrapper<BarcodeEntity>().eq("barcode", code).last("limit 1"));
        if (barcode != null) {
            barcode.setProduct(productService.getById(barcode.getProductId()));
        }
        return barcode;
    }

    @Override
    public BarcodeEntity queryInfoByBarcodeId(String barcodeId) {
        BarcodeEntity barcode = this.getOne(new QueryWrapper<BarcodeEntity>().eq("barcode_id", barcodeId).last("limit 1"));
        if (barcode != null) {
            barcode.setProduct(productService.getById(barcode.getProductId()));
        }
        return barcode;
    }

    @Override
    public boolean batchImportData(Collection<ImportBarcodeExcel> entityList) {
        for (ImportBarcodeExcel entity : entityList) {
            BarcodeEntity barcode = this.queryInfoByBarcodeId(entity.getBarcodeId());
            if (barcode == null) {
                barcode = new BarcodeEntity();
                BeanUtil.copyProperties(entity, barcode);
                ProductEntity product = productService.queryInfoByProductId(entity.getProductId());
                if (product != null) {
                    barcode.setBarcode(entity.getCode());
                    barcode.setProductId(product.getId());
                    barcode.setProductInfo(entity.getProductName() + "（" + product.getModel() + "）" + "【" + product.getFactory() + "】");
                    this.saveBarcode(barcode);
                } else {
                    logger.info(JSONObject.toJSONString(entity));
                }
            } else {
                BeanUtil.copyProperties(entity, barcode);
                ProductEntity product = productService.queryInfoByProductId(entity.getProductId());
                barcode.setBarcode(entity.getCode());
                barcode.setProductId(product.getId());
                barcode.setProductInfo(entity.getProductName() + "（" + product.getModel() + "）" + "【" + product.getFactory() + "】");
                this.updateBarcode(barcode);
            }
        }
        return true;
    }

    @Override
    public boolean saveBarcode(BarcodeEntity barcode) {
        return this.save(barcode);
    }

    @Override
    public boolean updateBarcode(BarcodeEntity barcode) {
        return this.updateById(barcode);
    }

    @Override
    public void deleteBarcode(Long barcodeId) {
        baseMapper.deleteById(barcodeId);
    }
}
